import { init, setConfig } from './src/main/ets/config'
import nfcDiscover from './src/main/ets/discover'
import { wifiConnect, WIFI_SECURITY_TYPE } from './src/main/ets/connect/wifi';
import { wifiMessage } from './src/main/ets/message/wifi';
import { waitTime } from './src/main/ets/util';

import type { DiscoverDevice, WifiInfo } from './src/main/ets/discover';
import type { WifiDeviceConfig } from './src/main/ets/connect/wifi';
import type { MessageHandler } from './src/main/ets/message/wifi';

export async function startDiscover(): Promise<boolean> {
  return await nfcDiscover.startFound()
}

export function stopDiscover(): boolean {
  return nfcDiscover.stopFound()
}

export async function connectDevice(wifiInfo: WifiInfo): Promise<boolean> {
  const config: WifiDeviceConfig = {
    ssid: wifiInfo.ssid,
    preSharedKey: wifiInfo.password || '',
    securityType: wifiInfo.password ? WIFI_SECURITY_TYPE.WIFI_SEC_TYPE_PSK : WIFI_SECURITY_TYPE.WIFI_SEC_TYPE_OPEN
  }
  let result = await wifiConnect.connect(config)
  if (result) {
    await waitTime(1000)
    result = await wifiMessage.create(wifiInfo.address)
  }
  return result
}

export async function authDevice(): Promise<boolean> {
  const result = await wifiMessage.auth()
  return result
}

export async function disconnectDevice(): Promise<boolean> {
  const result = wifiMessage.destroy()
  // const result2 = wifiConnect.disconnect()
  return result
}

export function onDeviceDiscover(handler: (device: DiscoverDevice) => void, key: string | symbol = Symbol()) {
  nfcDiscover.onDeviceDiscover(handler, key)
}

export function onMessage(handler: MessageHandler, key: string | symbol = Symbol()) {
  wifiMessage.omMessage(handler, key)
}

export async function sendMessage(message: string): Promise<boolean> {
  return wifiMessage.sendMessage(message)
}

export {
  init, setConfig
}

